package com.utils.mybatis;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class SqlUtil {

	
	
	/**
	 * 获取字符串某个字符的个数
	 * @param parameters
	 * @return
	 * @throws Exception 
	 */

	public  static int  getCharNum(String str,String ch) {
		return str.replace(" ", "").split(ch).length;
	}
	
	/**
	 * sql占位符替换
	 * @param parameters
	 * @return
	 * @throws Exception 
	 */
	public static String getSql(String sql,Object[] data) throws Exception {
		if (getCharNum(sql, "\\?")==data.length) {
			for (int i = 0; i < data.length; i++) {
				sql=sql.replaceFirst("\\?", "'"+ data[i]+"'");
			}
			return sql;
		}
		throw new Exception(sql+":sql占位符个数和参数个数不匹配");
	}
	
	/**
	 * 提取的sql语句表名（增删改查，返回单个表名）
	 * @param parameters
	 * @return
	 * @throws Exception 
	 */
	public  static String  getSqlTableName(String sql) {
		Pattern p=Pattern.compile("(.*into\\s*|.*from\\s*|.*update\\s*)([a-zA-Z|_|-]*)(.*)");        	
		sql=sql.replace("`", "");
		Matcher m=p.matcher(sql.toLowerCase());
    	if(m.find()){
    		return m.group(2).replace(" ", "");
    	}
		//没有匹配的返回空串
		return "";
	}
	
	
	
	/**
	 * query的sql语句提取表名,多个逗号隔开
	 * @param parameters
	 * @return
	 * @throws Exception 
	 */
	public  static String  getQuerySqlTableName(String sql,String table) {
		Pattern p=Pattern.compile("(.*from\\s*|.*join\\s*)([a-zA-Z|_|-]*)(.*)");        	
		sql=sql.replace("`", "");
		Matcher m=p.matcher(sql.toLowerCase());
		try {
			m.find();
			table=table+ m.group(2).replace(" ", "")+",";
			String group1=m.group(1);
			String group3=m.group(3);
			if (group1.contains("from")||group1.contains("join")) {
				table=getQuerySqlTableName(group1.substring(0, group1.length()-5),table);
			}
			if (group3.contains("from")||group3.contains("join")) {
				table=getQuerySqlTableName(group3,table);
			}
    		return table;
		}catch (Exception e) {
			return table;
		}


	}
	


	public static void main(String[] args) {
		String sql="delete from t_user";
		System.out.println(getQuerySqlTableName(sql,""));;
		System.out.println(getSqlTableName(sql));
	}
	
	
	/**
	 * 字符串倒序
	 * @param parameters
	 * @return
	 * @throws Exception 
	 */
	public  static String  reverseString (String sql) {
		String result="";
		for (int i = 0; i <sql.length(); i++) {
			String chars=sql.charAt(sql.length()-i-1)+"";
			result=result+chars;
		}
		return result;
	}
}
